using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using AutoMapper;
using HuiLian.Common.Input;
using HuiLian.Common.Output;
using HuiLian.Model.Platform;
using HuiLian.Repository.Platform;
using HuiLian.Service.Platform.Leakpoint.Input;
//using HuiLian.Service.Platform.Leakpoint.Output;
using HuiLian.Common.Attributes;
using HuiLian.Common;
using NPOI.SS.Formula.Functions;
using Microsoft.AspNetCore.Mvc;
using HuiLian.Service.Platform.Leakpoint.Output;

namespace HuiLian.Service.Platform.Leakpoint
{
    /// <summary>
    /// 漏水点记录服务
    /// </summary>
    public class LeakpointService : ILeakpointService
    {
        private readonly IMapper _mapper;
        private readonly ILeakpointRepository _leakpointRepository;
        private readonly IPipeRepository _pipeRepository;

        public LeakpointService(IMapper mapper, ILeakpointRepository leakpointRepository, IPipeRepository pipeRepository)
        {
            _mapper = mapper;
            _leakpointRepository = leakpointRepository;
            _pipeRepository = pipeRepository;
        }

        /// <summary>
        /// 获取漏水点记录信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<IResponseOutput> GetAsync(long id)
        {
            var result = await _leakpointRepository.GetAsync<LeakpointGetOutput>(id);
            return ResponseOutput.Ok(result);
        }

        /// <summary>
        /// 查询漏水点记录信息
        /// </summary>
        /// <param name="input">分页信息</param>
        /// <returns></returns>
        public async Task<IResponseOutput> PageAsync(PageInput<LeakpointEntity> input)
        {
            //var key = input.Filter?.Label;

            if(input.DynamicFilter != null && input.DynamicFilter.Filters != null && input.DynamicFilter.Filters.Count > 0)
            {
                foreach (var item in input.DynamicFilter.Filters)
                {
                    if(item.Field == "管线编号")
                    {
                        item.Field = "管段编号";
                    }
                }
            }

            var list = await _leakpointRepository.Select
            .WhereDynamicFilter(input.DynamicFilter)
            //.WhereIf(key.NotNull(), a => a.Path.Contains(key) || a.Label.Contains(key))
            .Count(out var total)
            .OrderBy(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync<LeakpointListOutput>(p => new LeakpointListOutput { 管线编号 = p.管段编号 });

            var data = new PageOutput<LeakpointListOutput>()
            {
                List = _mapper.Map<List<LeakpointListOutput>>(list),
                Total = total
            };

            return ResponseOutput.Ok(data);
        }

        /// <summary>
        /// 添加漏水点记录信息
        /// </summary>
        /// <param name="input">漏水点记录信息</param>
        /// <returns></returns>
        public async Task<IResponseOutput> AddAsync(LeakpointAddInput input)
        {
            var entity = _mapper.Map<LeakpointEntity>(input);
            var id = (await _leakpointRepository.InsertAsync(entity)).Id;

            return ResponseOutput.Result(id > 0);
        }

        /// <summary>
        /// 更新漏水点记录信息
        /// </summary>
        /// <param name="input">漏水点记录信息</param>
        /// <returns></returns>
        public async Task<IResponseOutput> UpdateAsync(LeakpointUpdateInput input)
        {
            if (!(input?.Id > 0))
            {
                return ResponseOutput.NotOk();
            }

            var entity = await _leakpointRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                return ResponseOutput.NotOk("数据不存在！");
            }

            _mapper.Map(input, entity);
            await _leakpointRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 删除漏水点记录信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<IResponseOutput> DeleteAsync(long id)
        {
            var result = false;
            if (id > 0)
            {
                result = (await _leakpointRepository.DeleteAsync(m => m.Id == id)) > 0;
            }

            return ResponseOutput.Result(result);
        }

        /// <summary>
        /// 软删除漏水点记录信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<IResponseOutput> SoftDeleteAsync(long id)
        {
            var result = await _leakpointRepository.SoftDeleteAsync(id);
            return ResponseOutput.Result(result);
        }

        /// <summary>
        /// 批量软删除漏水点记录信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> BatchSoftDeleteAsync(long[] ids)
        {
            var result = await _leakpointRepository.SoftDeleteAsync(ids);

            return ResponseOutput.Result(result);
        }

        /// <summary>
        /// 添加列表，如果实体Id存在，就不添加
        /// </summary>
        /// <param name="leakpoints"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> AddListAsync(List<LeakpointEntity> leakpoints)
        {
            var entitys = await _leakpointRepository.Select.ToListAsync();
            List<LeakpointEntity> addList = new List<LeakpointEntity>();
            foreach (var leakpoint in leakpoints)
            {
                var entity = entitys.Where(p => p.节点编号 == leakpoint.节点编号).FirstOrDefault();
                if (entity == null)
                {
                    if(!string.IsNullOrWhiteSpace(leakpoint.节点编号)) leakpoint.实体ID = leakpoint.节点编号.Replace("JD", "");
                    addList.Add(leakpoint);
                }
            }

            if(addList.Count > 0)
            {
                var count = (await _leakpointRepository.InsertAsync(addList)).Count;
                return ResponseOutput.Result(count > 0);
            }
            return ResponseOutput.Result(true);
        }

        /// <summary>
        /// 管网绑定
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> PipeBind(PipeBindInput input)
        {
            var entity = await _leakpointRepository.Select.Where(p => p.实体ID == input.实体ID).FirstAsync();
            if (entity == null)
            {
                return ResponseOutput.NotOk("数据不存在！");
            }

            var pipe = await _pipeRepository.Select.Where(p => p.管段编号 == input.管段编号).FirstAsync();
            if (pipe == null) return ResponseOutput.NotOk("管段数据不存在");

            if (pipe.管径 != entity.管径) return ResponseOutput.NotOk("漏水点和管线的管径不同，不能绑定");
            if (pipe.管材 != entity.管线材质) return ResponseOutput.NotOk("漏水点和管线的材质不同，不能绑定");

            entity.管段编号 = input.管段编号;
            await _leakpointRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 漏水点关联管线
        /// </summary>
        /// <param name="leakpoints"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> GuanLianPipeAsync(List<LeakpointEntity> leakpoints)
        {
            var entitys = await _leakpointRepository.Select.ToListAsync();
            List<LeakpointEntity> updateList = new List<LeakpointEntity>();
            foreach (var leakpoint in leakpoints)
            {
                var entity = entitys.Where(p => p.节点编号 == leakpoint.节点编号).FirstOrDefault();
                if (entity != null)
                {
                    entity.管段编号 = leakpoint.管段编号;
                    updateList.Add(entity);
                }
            }

            if (updateList.Count > 0)
            {
                var count = (await _leakpointRepository.UpdateAsync(updateList));
                return ResponseOutput.Result(count > 0);
            }
            return ResponseOutput.Result(true);
        }

        /// <summary>
        /// 更新管线的破损次数
        /// </summary>
        /// <returns></returns>
        public async Task<IResponseOutput> UpdateCount()
        {
            string sql = "update pipe set 破损次数=t.数量 from (select 管段编号,count(*) as 数量 from leakpoint where 管段编号 is not null group by 管段编号)as t where  pipe.管段编号=t.管段编号";
            await _leakpointRepository.Orm.Ado.ExecuteNonQueryAsync(sql);
            return ResponseOutput.Ok();
        }
    }
}
